package com.usefullc.english.controller;

import com.usefullc.english.domain.*;
import com.usefullc.english.enums.ContentStatusEnum;
import com.usefullc.english.enums.PracticeLevelEnum;
import com.usefullc.english.param.ReplyParam;
import com.usefullc.english.param.UserSubtitleParam;
import com.usefullc.english.param.UserWordDictParam;
import com.usefullc.english.param.WordDictParam;
import com.usefullc.english.query.*;
import com.usefullc.english.service.*;
import com.usefullc.english.vo.*;
import com.usefullc.common.constants.SystemConstant;
import com.usefullc.common.enums.YesNoEnum;
import com.usefullc.common.exception.BizException;
import com.usefullc.common.user.OnlineUser;
import com.usefullc.common.user.OnlineUserManager;
import com.usefullc.common.util.BeanUtils;
import com.usefullc.common.util.RequestUtils;
import com.usefullc.system.controller.WebResultBuilder;
import com.usefullc.system.entity.Pager;
import com.usefullc.system.entity.WebResult;
import com.usefullc.system.param.IdParam;
import com.usefullc.system.param.IdsParam;
import com.usefullc.system.service.component.extend.ExtendDataComponent;
import com.usefullc.system.validator.UsefulValid;
import com.usefullc.user.service.UserService;
import io.swagger.annotations.Api;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Sampson
 * @date: 2022-07-07 21:01
 */
@Controller
@RequestMapping("/cmsEnglish")
@Api( tags="英语练习前端页面")
public class EnglishController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private ExtendDataComponent extendDataComponent;

    @Autowired
    private ContentReadService contentReadService;

    @Autowired
    private ReplyService replyService;

    @Autowired
    private ReplyLikeService replyLikeService;

    @Autowired
    private ContentLikeService contentLikeService;

    @Autowired
    private ContentShareService contentShareService;

    @Autowired
    private TagService tagService;

    @Autowired
    private UserService userService;

    @Autowired
    private SubtitleService subtitleService;

    @Autowired
    private WordDictService wordDictService;

    @Autowired
    private UserWordDictService userWordDictService;

    @Autowired
    private UserSubtitleService userSubtitleService;


    @GetMapping({"/","","/index.html"})
    public String index( Model model) {
        return "public/index.html";
    }

    @GetMapping({"/register.html"})
    public String register( Model model) {
        return "public/register.html";
    }

    @GetMapping({"/login.html"})
    public String login( Model model) {
        return "public/login.html";
    }

    @GetMapping({"/logout.html"})
    public String logout(HttpServletRequest request, Model model) {
        userService.clearLoginUser(request);
        return "public/login.html";
    }


    @GetMapping({"/about.html"})
    public String about( Model model) {
//        contentService.dataFix();
        return "public/about.html";
    }


    @GetMapping({"/userCenter.html"})
    public String userCenter( Model model) {
//        contentService.dataFix();
        return "public/userCenter.html";
    }

    @GetMapping({"/settings.html"})
    public String settings( Model model) {
//        contentService.dataFix();
        return "public/userCenter/settings.html";
    }

    @GetMapping("/category/{sid}.html")
    public String contentList(@PathVariable("sid") String sid, Model model) {
        ContentQuery contentQuery = new ContentQuery();
        Long categoryId;
        if(sid.indexOf("-") > 0){
            categoryId = Long.valueOf(sid.split("-")[0]);
            contentQuery.setPageIndex(Integer.valueOf(sid.split("-")[1]));
        }else{
            categoryId = Long.valueOf(sid);
        }

        Category category = categoryService.findById(categoryId);
        CategoryVo categoryVo = BeanUtils.beanCopy(category,CategoryVo.class);

        List<Category> childrenList = categoryService.getChildrenByParentId(categoryId);
        if(CollectionUtils.isNotEmpty(childrenList)){
            List<CategoryVo> categoryVos = BeanUtils.listBeanCopy(childrenList, CategoryVo.class);
            categoryVo.setChildren(categoryVos);
        }

        categoryVo.setUrlPrefix(StringUtils.removeEnd(category.getUrl(),".html"));
        model.addAttribute("category",categoryVo);

        List<Category> childCategoryList = categoryService.getChildrenByCodeLike(category.getCode());
        List<Long> categoryIds = childCategoryList.stream().map(data -> data.getId()).collect(Collectors.toList());

        //获取文章列表
        categoryIds.add(categoryId);
        contentQuery.setCategoryIds(categoryIds);
        contentQuery.setStatus(ContentStatusEnum.RELEASED.getCode());
        contentQuery.setOrderByColumn("top,orderNo");
        contentQuery.setAscOrDesc("asc");
        Pager<ContentVo> pager = contentService.findCmsVoByPage(contentQuery);

        model.addAttribute("pager",pager);

        return "public/list.html";
    }


    @GetMapping("/tag/{tagId}.html")
    public String tagContentList(@PathVariable("tagId") Long tagId, Model model) {
        TagQuery tagQuery = new TagQuery();
        tagQuery.setId(tagId);
        Pager<ContentVo> pager = contentService.findCmsPageVoByTag(tagQuery);
//        ContentQuery contentQuery = new ContentQuery();
//        Long categoryId;
//        if(sid.indexOf("-") > 0){
//            categoryId = Long.valueOf(sid.split("-")[0]);
//            contentQuery.setPageIndex(Integer.valueOf(sid.split("-")[1]));
//        }else{
//            categoryId = Long.valueOf(sid);
//        }

//        Category category = categoryService.findById(categoryId);
        CategoryVo categoryVo = new CategoryVo();
        categoryVo.setUrlPrefix("/cmsEnglish/tag/"+tagId);
        categoryVo.setUrl("/cmsEnglish/tag/"+tagId+".html");
        Tag tag = this.tagService.findById(tagId);
        categoryVo.setName(tag.getName());
//        categoryVo.setUrlPrefix(StringUtils.removeEnd(category.getUrl(),".html"));
        model.addAttribute("category",categoryVo);

//        List<Category> childCategoryList = categoryService.getChildrenByCodeLike(category.getCode());
//        List<Long> categoryIds = childCategoryList.stream().map(data -> data.getId()).collect(Collectors.toList());

//        //获取文章列表
//        categoryIds.add(categoryId);
//        contentQuery.setCategoryIds(categoryIds);
//        contentQuery.setStatus(ContentStatusEnum.RELEASED.getCode());
//        Pager<ContentVo> pager = contentService.findCmsVoByPage(contentQuery);

        model.addAttribute("pager",pager);

        return "public/list.html";
    }



    @GetMapping("/content/{contentId}.html")
    public String content(@PathVariable("contentId") Long contentId, Model model, HttpServletRequest request) {

        Content content = this.contentService.findById(contentId);

        //记录阅读数量
        contentService.doRead(contentId);

        Long categoryId = content.getCategoryId();

        Category category = categoryService.findById(categoryId);
        CategoryVo categoryVo = BeanUtils.beanCopy(category,CategoryVo.class);

        List<Category> childrenList = categoryService.getChildrenByParentId(categoryId);
        if(CollectionUtils.isNotEmpty(childrenList)){
            List<CategoryVo> categoryVos = BeanUtils.listBeanCopy(childrenList, CategoryVo.class);
            categoryVo.setChildren(categoryVos);
        }
        model.addAttribute("category",categoryVo);

        if(category.getParentId() == 0){
            Category parentCategory = new Category();
            parentCategory.setUrl("/");
            parentCategory.setName("首页");
            model.addAttribute("parentCategory",parentCategory);
        }else{
            Category parentCategory = categoryService.findById(category.getParentId());
            model.addAttribute("parentCategory",parentCategory);
        }

        model.addAttribute("content",contentService.wrapperCmsContent(content));

        ContentQuery contentQuery = new ContentQuery();

        contentQuery.setOrderNoEnd(content.getOrderNo());
        contentQuery.setOrderByColumn("orderNo");
        contentQuery.setAscOrDesc("desc");
        contentQuery.setCategoryId(categoryId);
        contentQuery.setResultLimit(1);
        Content preContent = contentService.findOne(contentQuery);
        model.addAttribute("preContent",contentService.wrapperCmsContent(preContent));

        contentQuery = new ContentQuery();
        contentQuery.setOrderNoStart(content.getOrderNo());
        contentQuery.setOrderByColumn("orderNo");
        contentQuery.setAscOrDesc("asc");
        contentQuery.setCategoryId(categoryId);
        contentQuery.setResultLimit(1);
        Content nextContent = contentService.findOne(contentQuery);
        model.addAttribute("nextContent",contentService.wrapperCmsContent(nextContent));


        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser == null){
            model.addAttribute("logined",false);
        }else{
            //点赞
            model.addAttribute("logined",true);
            model.addAttribute("user",loginUser);
//            model.addAttribute("userId",loginUser.getUserId());
            ContentLikeQuery contentLikeQuery = new ContentLikeQuery();
            contentLikeQuery.setUserId(loginUser.getUserId());
            contentLikeQuery.setContentId(contentId);
            contentLikeQuery.setStatus(YesNoEnum.YES.getCode());
            ContentLike contentLike = contentLikeService.findOne(contentLikeQuery);
            if(contentLike != null){
                model.addAttribute("liked",true);
            }

            contentLikeQuery = new ContentLikeQuery();
            contentLikeQuery.setContentId(contentId);
            contentLikeQuery.setStatus(YesNoEnum.YES.getCode());
            long likeNum = contentLikeService.count(contentLikeQuery);
            model.addAttribute("likeNum",likeNum);

            //评论
            ReplyQuery replyQuery = new ReplyQuery();
            replyQuery.setContentId(contentId);
            replyQuery.setUserId(loginUser.getUserId());
            long replyNum = replyService.count(replyQuery);
            model.addAttribute("replyNum",replyNum);

            replyQuery = new ReplyQuery();
            replyQuery.setContentId(contentId);
            List<ReplyVo> replyDataList = replyService.findVoByPage(replyQuery).getDataList();

            model.addAttribute("replyDataList",replyDataList);
        }

        return "public/info.html";
    }


    //阅读
    //点赞
    @ResponseBody
    @PostMapping({"/like"})
    public WebResult like(@UsefulValid @RequestBody IdParam param) {
        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser == null){
            throw new BizException(SystemConstant.ResponseCode.NOT_LOGIN,"请先登录");
        }
        boolean result = contentLikeService.like(param.getId(),loginUser.getUserId(), RequestUtils.getClientIpAddr());
        return WebResultBuilder.successResult(result);
    }

    @ResponseBody
    @PostMapping({"/unLike"})
    public WebResult unLike(@UsefulValid @RequestBody IdParam param) {
        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser == null){
            throw new BizException(SystemConstant.ResponseCode.NOT_LOGIN,"请先登录");
        }
        boolean result = contentLikeService.unLike(param.getId(),loginUser.getUserId());
        return WebResultBuilder.successResult(result);
    }

    //回复
    @ResponseBody
    @PostMapping({"/reply"})
    public WebResult reply(@UsefulValid(save = true) @RequestBody ReplyParam param) {
        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser == null){
            throw new BizException(SystemConstant.ResponseCode.NOT_LOGIN,"请先登录");
        }

        Reply reply = BeanUtils.beanCopy(param,Reply.class);
        reply.setUserId(loginUser.getUserId());
        boolean result = replyService.save(reply);
        return WebResultBuilder.successResult(result);
    }
    //删除回复
    //回复列表

    @ResponseBody
    @GetMapping({"/getSubtitleListByContentId"})
    public WebResult getSubtitleListByContentId(@UsefulValid UserSubtitleParam param) {
        List<SubtitleVo> dataList = subtitleService.subtitleList(param.getContentId(),param.getCollect(),param.getPracticeLevel());
        return WebResultBuilder.successResult(dataList);
    }


    @ResponseBody
    @GetMapping({"/getWordDict"})
    public WebResult getWordDict(@UsefulValid WordDictParam param) {
        WordDictVo wordDict = wordDictService.findByNameOrBuild(param.getName());
        //是否收藏
        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser != null){
            UserWordDictQuery userWordDictQuery = new UserWordDictQuery();
            userWordDictQuery.setUserId(loginUser.getUserId());
            userWordDictQuery.setWordDictId(wordDict.getId());
            UserWordDict userWordDict = userWordDictService.findOne(userWordDictQuery);
            wordDict.setCollect(userWordDict != null && userWordDict.getStatus() == YesNoEnum.YES.getCode());
        }
        return WebResultBuilder.successResult(wordDict);
    }


    @ResponseBody
    @PostMapping({"/wordCollect"})
    public WebResult wordCollect(@UsefulValid(save = true) @RequestBody UserWordDictParam param) {
        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser == null){
            throw new BizException(SystemConstant.ResponseCode.NOT_LOGIN,"请先登录");
        }
        UserWordDict userWordDict = new UserWordDict();
        userWordDict.setUserId(loginUser.getUserId());

        WordDictVo wordDict = wordDictService.findByName(param.getName());
        userWordDict.setWordDictId(wordDict.getId());
        userWordDict.setContentId(wordDict.getId());
        userWordDict.setStatus(param.getStatus());

        try{
            UserWordDictQuery userWordDictQuery = new UserWordDictQuery();
            userWordDictQuery.setWordDictId(wordDict.getId());
            userWordDictQuery.setUserId(loginUser.getUserId());
            UserWordDict oldBean = userWordDictService.findOne(userWordDictQuery);
            if(oldBean != null){
                userWordDict.setId(oldBean.getId());
                userWordDictService.update(userWordDict);
            }else{
                userWordDictService.save(userWordDict);
            }
        }catch (Exception e){
        }
        return WebResultBuilder.successResult(wordDict);
    }


    @ResponseBody
    @PostMapping({"/subtitleCollect"})
    public WebResult subtitleCollect(@UsefulValid(save = true) @RequestBody UserSubtitleParam param) {
        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser == null){
            throw new BizException(SystemConstant.ResponseCode.NOT_LOGIN,"请先登录");
        }
        UserSubtitle userSubtitle = new UserSubtitle();
        userSubtitle.setUserId(loginUser.getUserId());
        userSubtitle.setSubtitleId(param.getSubtitleId());
        Subtitle subtitle = subtitleService.findById(param.getSubtitleId());
        userSubtitle.setContentId(subtitle.getContentId());
        userSubtitle.setCollect(param.getCollect());
        try{
            UserSubtitleQuery userSubtitleQuery = new UserSubtitleQuery();
            userSubtitleQuery.setUserId(loginUser.getUserId());
            userSubtitleQuery.setSubtitleId(param.getSubtitleId());
            UserSubtitle oldBean = userSubtitleService.findOne(userSubtitleQuery);
            if(oldBean != null){
                userSubtitle.setId(oldBean.getId());
                BeanUtils.beanCopy(userSubtitle,oldBean);
                userSubtitleService.update(oldBean);
            }else{
                userSubtitle.setPracticeLevel(PracticeLevelEnum.NOTHING.getCode());
                userSubtitleService.save(userSubtitle);
            }
        }catch (Exception e){
        }
        return WebResultBuilder.successResult(userSubtitle);
    }


    @ResponseBody
    @PostMapping({"/setSubtitlePracticeLevel"})
    public WebResult setSubtitlePracticeLevel(@UsefulValid(save = true) @RequestBody UserSubtitleParam param) {
        OnlineUser loginUser = OnlineUserManager.getLoginUser();
        if(loginUser == null){
            throw new BizException(SystemConstant.ResponseCode.NOT_LOGIN,"请先登录");
        }
        UserSubtitle userSubtitle = new UserSubtitle();
        userSubtitle.setUserId(loginUser.getUserId());
        userSubtitle.setSubtitleId(param.getSubtitleId());
        Subtitle subtitle = subtitleService.findById(param.getSubtitleId());
        userSubtitle.setContentId(subtitle.getContentId());
        userSubtitle.setPracticeLevel(param.getPracticeLevel());
        try{
            UserSubtitleQuery userSubtitleQuery = new UserSubtitleQuery();
            userSubtitleQuery.setUserId(loginUser.getUserId());
            userSubtitleQuery.setSubtitleId(param.getSubtitleId());
            UserSubtitle oldBean = userSubtitleService.findOne(userSubtitleQuery);
            if(oldBean != null){
                userSubtitle.setId(oldBean.getId());
                BeanUtils.beanCopy(userSubtitle,oldBean);
                userSubtitleService.update(oldBean);
            }else{
                userSubtitle.setCollect(YesNoEnum.NO.getCode());
                userSubtitleService.save(userSubtitle);
            }
        }catch (Exception e){
        }
        return WebResultBuilder.successResult(userSubtitle);
    }




}
